package com.seven.first.suite.util;
public class IpV4Util {

    public static void main(String[] args) {
      //  System.out.println(compare("192.168.207.23","1.1.1.11"));
//        System.out.println(compare("192.168.207.23","200.1.1.1"));
//
 //       System.out.println(between(" 192.168.207.23","1.1. 1.11","200.1.1.1"));

    }


    public static boolean between(String ip,String ipStart,String ipEnd){
        return compare(ipStart,ip) <= 0 && compare(ip,ipEnd) <= 0;
    }

    public static int compare(String ip1,String ip2) {
        long ipValue1 = getIpValue(ip1);     // 获取ip1的32bit值
        long ipValue2 = getIpValue(ip2); // 获取ip2的32bit值

        if(ipValue1 > ipValue2) {
            return 1;
        }else if(ipValue1 < ipValue2) {
            return -1;
        }else {
            return 0;
        }
    }

    private static long getIpValue(String ipSrc){
        String[] ipParts = ipSrc.split("\\.");

        assert ipParts == null;

        StringBuilder uninIpStr = new StringBuilder();

        for ( String ipStr : ipParts){
            uninIpStr.append(String.format("%03d",Integer.valueOf(ipStr.trim())));
        }

        return Long.valueOf(uninIpStr.toString());
    }


//    private static int getIpV4Value(String ipOrMask) {
//        byte[] addr = getIpV4Bytes(ipOrMask);
//        int address1  = addr[3] & 0xFF;
//        address1 |= ((addr[2] << 8) & 0xFF00);
//        address1 |= ((addr[1] << 16) & 0xFF0000);
//        address1 |= ((addr[0] << 24) & 0xFF000000);
//        return address1;
//    }
//    private static byte[] getIpV4Bytes(String ipOrMask) {
//        try{
//            String[] addrs = ipOrMask.split("\\.");
//            int length = addrs.length;
//            byte[] addr = new byte[length];
//            for (int index = 0; index < length; index++)
//            {
//                addr[index] = (byte) (Integer.parseInt(addrs[index]) & 0xff);
//            }
//            return addr;
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return new byte[4];
//    }
}
